<?php
/**
 * ApiSpider.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/19- 下午8:27
 */

namespace common\drivers\spiderProduct;


use api\exceptions\CopyException;
use common\constants\PlatformConst;
use common\drivers\interfaces\SpiderProductInterface;
use common\exception\DriverException;
use common\helpers\AmountHelper;
use common\helpers\StringHelper;
use common\helpers\UrlsHelper;
use console\components\helpers\ConsoleHelper;

class ApiSpider extends BaseSpider implements SpiderProductInterface
{

    /**
     * 获取商品数据接口
     * @var string
     */
    protected $requestUrl = 'http://api.goods.mebei.net';
    /**
     * 失败重试3次
     * @var int
     */
    protected $tryTimes = 3;


    protected $platform = null;

    /**
     * 获取api数据
     * @param string $url
     * @return string
     * @throws DriverException
     */
    public function getContents(string $url): string
    {

        $this->platform = UrlsHelper::getUrlSource($url);


        $num_iid = UrlsHelper::getUrlPrimaryKey($this->platform,$url);


        $contentTimes = 0;
        while($contentTimes < $this->tryTimes)
        {
            $this->requestUrl .= '?goods_id='.$num_iid.'&platform='.PlatformConst::mappingApi($this->platform);


            $resources = $this->spiderContent($this->requestUrl);

            if(!$resources)
            {
                throw new DriverException('获取数据源失败');
            }
            $contents = $resources->getBody()->getContents();
            if(!$contents)
            {
                $contentTimes++;
                ConsoleHelper::runInfo("抓取api货源信息失败，即将重试第{$contentTimes}次");
                continue;
            }
            $this->resources = $contents;
            break;
        }

        if(!$this->resources)
        {
            throw new DriverException('获取数据源失败');
        }

        return $this->resources;
    }

    /**
     * @inheritDoc
     * @return array
     * @throws DriverException
     */
    public function formatContents(): array
    {
        $this->resources = StringHelper::jsonDecode($this->resources);

        if(!isset($this->resources['data']) || empty($this->resources['data']))
        {
            throw new DriverException('数据源不存在或已下架');
        }

        $this->productInfo['platform'] = $this->platform;

        $this->productInfo['mall_name'] = isset($this->resources['data']['mall_name']) && !empty($this->resources['data']['mall_name']) ?
            trim($this->resources['data']['mall_name']) : '';

        $this->productInfo['mall_id'] = $this->resources['data']['mall_id'] ?? 0;

        $this->productInfo['title'] = $this->resources['data']['title'] ?? '';
        $this->productInfo['prices'] = isset($this->resources['data']['price']) ? intval($this->resources['data']['price']) : 0;

        $this->productInfo['num_iid'] = $this->resources['data']['goods_id'] ?? 0;

        $this->productInfo['main_pic'] = $this->resources['data']['thumb'] ?? '';

        if(isset($this->resources['data']['video']) &&  !empty($this->resources['data']['video']))
        {
            $this->productInfo['video'] = $this->resources['data']['video'];
        }
        $this->productInfo['pics'] = StringHelper::jsonDecode($this->resources['data']['main_figures']); //主图

        $this->productInfo['detail_gallery'] = StringHelper::jsonDecode($this->resources['data']['detail_figures']); //详情图
        //商品详情，纯文本
        $this->productInfo['goods_desc'] = $this->resources['data']['desc'] ?? '';

        //属性
        if(isset($this->resources['data']['properties']) && !empty($this->resources['data']['properties']))
        {
            $properties =StringHelper::jsonDecode($this->resources['data']['properties']);

            if(is_array($properties) && count($properties))
            {
                $this->productInfo['attr'] = $properties;
            }
        }
        /**
         * sku 设置
         */
        $this->setSku();

        $this->setPcDesc();

        /**
         * 其他扩展字段
         */
        $this->setExtend();


        return $this->productInfo;

    }




    private function setExtend()
    {
        $this->productInfo['extend_data'] = [
            'fav_count' => $this->resources['data']['fav_count'] ?? 0, //收藏量
            'total_sold' => $this->resources['data']['total_sold'] ?? 0, //评论数
            'sales' => $this->resources['data']['sold_total'] ?? 0, //销量
            'pre_sale_stamp' => $this->resources['data']['pre_sale_stamp'] ?? 0, //预售时间，单位秒
            'post_fee' => $this->resources['data']['post_fee'] ?? 0, //物流费用
            'express_fee' => $this->resources['data']['express_fee'] ?? 0, //快递费用
            'location' => $this->resources['data']['location'] ?? '', //发货地
            'mall_goods_num' => $this->resources['data']['mall_goods_num'] ?? 0, //店铺所有商品数量
            'mall_sold_total' => $this->resources['data']['mall_sold_total'] ?? 0, //店铺所有商品总销量
            'delivery_time' => $this->resources['data']['delivery_time'] ?? '', //承诺多长时间发货，单位小时
        ];
    }

    /**
     * 设置sku信息
     */
    protected function setSku()
    {
        $propsList = $propsType = [];

        if(isset($this->resources['data']['sku_products']) && !empty($this->resources['data']['sku_products']))
        {
            $propsList = StringHelper::jsonDecode($this->resources['data']['sku_products']);
        }

        if(isset($this->resources['data']['sku_big_types']) && !empty($this->resources['data']['sku_big_types']))
        {
            $propsType = StringHelper::jsonDecode($this->resources['data']['sku_big_types']);
        }
//
//        print_r($propsList);
//        print_r($propsType); exit;

        $transSkuIds = [];
        /**
         * skuImg
         */
        if(count($propsType))
        {
            foreach ($propsType as $t => $propImg)
            {
                if(is_array($propImg['values']))
                {
                    foreach ($propImg['values'] as $_v => $val)
                    {
                        //只取第一条作为颜色图sku
                        if($t == 0)
                        {
                            $tmp = [];
                            $tmp['name'] = $propImg['name'];
                            $tmp['value'] = $val;
                            $tmp['skuImg'] = '';
                            $tmp['key'] = ($t+1).':'.$_v;
                            $this->productInfo['sku_img'][$_v] = $tmp;
                        }
                        $transSkuIds[$_v] = ['name'=>$propImg['name'].':'.$val,'ids'=>($t+1).':'.$_v];
                    }
                }
            }
        }
        /**
         * sku
         *  "properties":"["20509:12430610","1627207:28321"]",
         *  "properties_name":"["尺码:M（56-58cm）","颜色分类:白色"]",
         */
        if(count($propsList))
        {
            foreach($propsList as $k => $sku)
            {
                $tmp = [];
                $tmp['skuId'] = $sku['id'] ?? 0;
                $tmp['stock'] = $sku['quantity'] ?? 0;
                $tmp['price'] = isset($sku['price']) ? AmountHelper::fenToYuan((int)$sku['price']) : 0; //原价
                $tmp['sale_price'] = isset($sku['sale_price']) ? AmountHelper::fenToYuan((int)$sku['sale_price']) : $tmp['price']; //销售价
                $tmp['properties'] = [];
                $tmp['properties_name'] = [];
                $tmp['cover'] = $sku['url'] ?? ''; //防止sku中存在没有图片的情况导致数据格式不一致
                if(is_array($sku['skus']))
                {
                    foreach($sku['skus'] as $props)
                    {
                        if(isset($transSkuIds[$props]))
                        {
                            array_push($tmp['properties'],$transSkuIds[$props]['ids']);
                            array_push($tmp['properties_name'],$transSkuIds[$props]['name']);
                        }
                    }

                    foreach ($this->productInfo['sku_img'] as $p => $prop)
                    {
                        if(in_array($p,$sku['skus']))
                        {
                            $this->productInfo['sku_img'][$p]['skuImg'] = $sku['url'];
                        }
                    }
                }
                $tmp['properties_name'] = StringHelper::jsonEncode($tmp['properties_name']);
                $tmp['properties'] = StringHelper::jsonEncode($tmp['properties']);
                array_push($this->productInfo['skus'],$tmp);
            }
        }
        $this->productInfo['sku_img'] = array_values($this->productInfo['sku_img']);
    }

    /**
     * @inheritDoc
     */
    public function setErrorInfo(string $msg = '')
    {

    }

    /**
     * 设置下电脑端的描叙详情
     */
    private function setPcDesc()
    {
        if(count($this->productInfo['detail_gallery']))
        {
            $pc_desc = '<p>';
            foreach ($this->productInfo['detail_gallery'] as $k => $img)
            {
                $pc_desc .= '<img src="'.$img.'" align="absmiddle" />';
            }
            $pc_desc .='</p>';

            $this->productInfo['pc_desc'] = $pc_desc;
        }
    }

    /**
     * @inheritDoc
     */
    public function getErrorInfo()
    {
        return $this->errorInfo;
    }

    /**
     * @inheritDoc
     */
    public function saveDb()
    {

    }
}